package cn.fss.elasticsearch.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import cn.fss.elasticsearch.domain.SearchReq;
import cn.fss.common.core.page.TableDataInfo;
import cn.fss.common.utils.uuid.UUID;
import cn.fss.elasticsearch.ElasticSearchClient;
import cn.fss.elasticsearch.domain.DocumentObj;
import cn.fss.elasticsearch.service.ISearchSerice;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SearchServiceImpl implements ISearchSerice {

	@Autowired
	private ElasticSearchClient esClient;

	@Override
	public TableDataInfo search(SearchReq req) {
		String keyword = req.getKeyword();
		Integer pageSize  =req.getPageSize();
		Integer pageNum = req.getPageNum();
		Integer from = (pageNum-1)*pageSize;
		// 高亮查询，关键词添加红色样式
		HighlightBuilder highlightBuilder = new HighlightBuilder().field("attachment.content")
				.preTags("<font color='red' font-weight='bold'>").postTags("</font>");
		// 普通全索引查询
		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
				.query(QueryBuilders.matchQuery("attachment.content", keyword).analyzer("ik_smart"))
				.from(from).size(pageSize) //分页
				.trackTotalHits(true) //返回总数
				.highlighter(highlightBuilder);
		TableDataInfo datas = esClient.selectDocumentList( ISearchSerice.INDEX_DEFAULT_NAME, searchSourceBuilder);
		if(datas==null || CollectionUtils.isEmpty(datas.getRows())) {
			return null;
		}
		Long total = datas.getTotal();//总命中数
		
		@SuppressWarnings("unchecked")
		List<SearchHit> searchHits = (List<SearchHit>) datas.getRows();
		
		// 处理每一条记录(每一个文档)，获得高亮文本。
		List<DocumentObj> results = new ArrayList<>();
		for (SearchHit hit : searchHits) {
			Map<String, Object> sourceAsMap = hit.getSourceAsMap();
			DocumentObj obj = new DocumentObj();
			obj.setDocId(((Integer) sourceAsMap.get("docId")).intValue());
			obj.setDocName((String) sourceAsMap.get("docName"));
			obj.setDocType((String) sourceAsMap.get("docType"));
			obj.setTitle((String) sourceAsMap.get("title"));

			HighlightField contentHighlightField = hit.getHighlightFields().get("attachment.content");
			// 对于一个文档，它的高亮文本有多个结果，这里只拼接前2个结果。
			Text[] fragments = contentHighlightField.fragments();
			StringBuffer highLightMessage = new StringBuffer();
			if (fragments != null && fragments.length > 0) {
				for (Text t : fragments) {
					highLightMessage.append(t.toString()).append("|");
				}
			}
			if (StringUtils.isNoneBlank(highLightMessage.toString())) {
				obj.setContent(highLightMessage.toString());
				results.add(obj);

			}
		}
		TableDataInfo rst = new TableDataInfo();
		rst.setRows(results);
		rst.setTotal(total);
		return rst;

	}

	@Override
	public Boolean uploadFile(DocumentObj data) {
		try {
            //String id = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
			Boolean rst= esClient.insertDocument( ISearchSerice.INDEX_DEFAULT_NAME,data.getDocId()+"", data);
			return rst;
			
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return false;
	}

	@Override
	public boolean deleteDocumnet(String index, String docId) {
		if(StringUtils.isBlank(index)) {
			index = ISearchSerice.INDEX_DEFAULT_NAME;
		}
		return esClient.deleteDocument(index, docId);
	}

}
